package com.edgclub.edg.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.baseproject.utils.Logger;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.BBDetailAdapter;
import com.edgclub.edg.adapter.BBDetailLikeUserAdapter;
import com.edgclub.edg.adapter.RewardAdapter;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.RechargeApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.api.param.RechargeParam;
import com.edgclub.edg.api.param.TopicReportParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.AaskBeanData;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.RedOpenEntity;
import com.edgclub.edg.model.Reply;
import com.edgclub.edg.model.Topic;
import com.edgclub.edg.model.TopicChannel;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.RedOpenData;
import com.edgclub.edg.model.result.RewardUser;
import com.edgclub.edg.model.result.RewardUserComparator;
import com.edgclub.edg.model.result.Rewards;
import com.edgclub.edg.model.result.TopicDetailData;
import com.edgclub.edg.shareapi.ShareSDKApi;
import com.edgclub.edg.uc.ChannelsSelectDialog;
import com.edgclub.edg.uc.DeleteDialog;
import com.edgclub.edg.uc.GoldDialog;
import com.edgclub.edg.uc.MenuPopWindow;
import com.edgclub.edg.uc.OpenRedDialog;
import com.edgclub.edg.uc.TopicDetailDialog;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.ActivityUtil;
import com.edgclub.edg.utils.util.CommonUtils;
import com.edgclub.edg.utils.util.DensityUtils;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.MediaPlayerUtil;
import com.edgclub.edg.utils.util.NetworkUtility;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.rockerhieu.emojicon.EmojiconTextView1;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;
import com.youku.player.base.YoukuBasePlayerManager;
import com.youku.player.base.YoukuPlayer;
import com.youku.player.base.YoukuPlayerView;
import com.youku.player.plugin.YoukuPlayerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2016/5/20.
 */
public class GzTopicDetailActivity extends GzBaseTooolBarActivity implements View.OnClickListener, VolleyListener {

    // 回复贴子
    public static final int REQUEST_CODE_REPLYTOPIC = 0x1111;

    private Activity mActivity;

    private XRecyclerView recyclerView;
    private BBDetailAdapter bbAdapter;
    private View headView;
    private LinearLayout topic_bar;

    private String topicId;
    private Topic topic;
    private ArrayList<User> likeUsers;
    private boolean fristInActivity = true;
    private int currPage = 1;
    private int pageSize = 30;
    private boolean isLoading = false;
    private User user;
    private String isOwner = "false";  //false 查看全部,true 只看楼主
    private String order = "1"; //0：正序 1:倒序

    private TopicApi topicApi;
    private RechargeApi rechargeApi;
    private GlideUtils glideUtils;
    private ArrayList<Reply> detailList;

    /***********
     * 头部
     ***************/
    private EmojiconTextView1 topic_content;
    private TextView topic_time, user_name;
    private ImageView user_icon, isvip;
    private RecyclerView unableScrollRecycleView;
    private RelativeLayout ll_like, ll_red_packet;
    private RecyclerView likeRecycleView;
    private TextView tv_like_num;
    //语音
    ImageView iv_voice, iv_voice_bg;
    RelativeLayout ll_voice;
    TextView tv_length;
    private MediaPlayerUtil mediaPlayerUtil;
    private AnimationSet set;
    private AnimationDrawable voiceAnimation = null;
    //位置
    TextView topic_city;
    LinearLayout topic_locaiton_layout;
    //video
//    private ImageView image_play;
    /***********
     * 底部
     ***************/
    private TextView tv_zan, tv_comment;
    private ImageView imgv_star1, imgv_star2, imgv_zan;
    private LinearLayout ll_bottom;
    private RelativeLayout tv_reward;
    private int spacingInPixels;

    // PopupWindow
    private MenuPopWindow menuPopWindow;
    private boolean isMyTopic = false;

    private BBDetailLikeUserAdapter likeUserAdapter;
    private UserPrefUtils userPrefUtils;

    private boolean isShowCommentDialog = false;


    //点赞动画
    private ScaleAnimation scaleAnimation;
    private AnimationSet starSet;

    private String nice = "0"; //0 未加精,  1 已加精

    //打赏
    private Rewards rewards;
    private int reward_gold;

    private ArrayList<TopicChannel> channels;

    private String redState = "0";

    @Override
    public int getContentView() {
        return R.layout.activity_topic_detail;
    }

    @Override
    public void setTitleBarView() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 出现初始化错误
        try {
            initVideoView();
        } catch (Exception e) {
            e.printStackTrace();
        }
        setCustomActionBar();
        userPrefUtils = new UserPrefUtils(this);
        title.setText("帖子详情");
        btn_collect.setVisibility(View.VISIBLE);
        btn_more_menu.setVisibility(View.VISIBLE);
        imgv_more.setImageResource(R.drawable.reward_img);
        btn_collect.setOnClickListener(this);
        btn_more_menu.setOnClickListener(this);
        main_back.setOnClickListener(this);

    }

    @Override
    public void initView() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(myNetReceiver, mFilter);
        mActivity = this;
        spacingInPixels = DensityUtils.dip2px(this, 12);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
        tv_reward = (RelativeLayout) findViewById(R.id.tv_reward);
        tv_zan = (TextView) findViewById(R.id.tv_zan);
        imgv_star1 = (ImageView) findViewById(R.id.imgv_star1);
        imgv_star2 = (ImageView) findViewById(R.id.imgv_star2);
        imgv_zan = (ImageView) findViewById(R.id.imgv_zan);
        tv_comment = (TextView) findViewById(R.id.tv_comment);
        ll_bottom = (LinearLayout) findViewById(R.id.ll_bottom);
//        image_play = (ImageView) findViewById(R.id.image_play);
//        image_play.setOnClickListener(this);
        tv_comment.setOnClickListener(this);
        findViewById(R.id.ll_zan).setOnClickListener(this);
        tv_reward.setOnClickListener(this);

        recyclerView = (XRecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

//        headView =   LayoutInflater.from(this).inflate(R.layout.head_bb_detail, (ViewGroup)findViewById(android.R.id.content),false);
//        initHeadView(headView);
//        recyclerView.addHeaderView(headView);
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currPage = 1;
                getDetailReply();
            }

            @Override
            public void onLoadMore() {
                getDetailReply();
            }
        });

    }


    @Override
    public void initData() {
        redState = getIntent().getStringExtra("redState");
        recyclerView.setPullRefreshEnabled(false);
        showDialog1();
        scaleAnimation = new ScaleAnimation(1.0f,
                2.0f, 1.0f, 2.0f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(400);

        //点赞星星动画
        starSet = new AnimationSet(true);
        ScaleAnimation starScaleAnimation = new ScaleAnimation(0.5f, 1.5f, 1.0f, 1.5f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        starScaleAnimation.setDuration(400);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(400);
        starSet.addAnimation(starScaleAnimation);
        starSet.addAnimation(alphaAnimation);

        user = new UserPrefUtils(this).getUser();
        topicApi = new TopicApi(this);
        rechargeApi = new RechargeApi(this);
        glideUtils = new GlideUtils();
        detailList = new ArrayList<>();
        bbAdapter = new BBDetailAdapter(this);
        bbAdapter.setDetailDatas(detailList);
        bbAdapter.setReplyOnclickListener(new MyReplyClickListener());
        bbAdapter.setOpenRedClickListener(new MyOpenRedClickListener());
        bbAdapter.setAddRewardClickListener(new addRewardClickListener());
        recyclerView.setAdapter(bbAdapter);
        topicId = getIntent().getStringExtra("topicId");
        isShowCommentDialog = getIntent().getBooleanExtra("isShowCommentDialog", false);
        if (isShowCommentDialog) {
            Intent intent = new Intent(GzTopicDetailActivity.this,
                    GzTopicReplyTopicActivity.class);
            intent.putExtra("topicId", topicId);
            startActivityForResult(intent, REQUEST_CODE_REPLYTOPIC);
        }

        getDetailReply();

    }


    private void getDetailReply() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setPage(currPage + "");
        postsParam.setPageSize(pageSize + "");
        postsParam.setUserId(user.getId() + "");
        postsParam.setOrder(order);
        postsParam.setIsOwner(isOwner); //false 查看全部,true 只看楼主
        topicApi.detailPost(postsParam, this);
    }

    @Override
    public void onStart(String tag) {

        isLoading = true;
        if (fristInActivity) {
            showDialog("正在获取...", true);
            fristInActivity = false;
        }

        if (tag.equals(ApiConfig.APIURL.URL_POSTS_DELETE)) {
            showDialog("正在删除...", true);
        } else if (tag.equals(ApiConfig.APIURL.URL_POSTS_ADD_TO_DIGEST)) {
            showDialog("正在加精...", true);
        }
    }

    @Override
    public void onSuccess(String response, String tag) {
        isLoading = false;
        int code = JSONHelper.getResultCode(response);
        dismissDialog();
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        if (JSONHelper.isSuccess(response)) {
            if (tag.equals(ApiConfig.APIURL.URL_POSTS_DETAIL)) {
                TopicDetailData data = JsonUtil.getMode(response, TopicDetailData.class);
//                setHeadContent(topic);
                if (currPage == 1) {
                    topic = data.getData().getPosts();
                    likeUsers = data.getData().getLikeUsers();
                    rewards = data.getData().getRewards();
                    bbAdapter.setTopic(topic);
                    bbAdapter.setLikeUsers(likeUsers);
                    bbAdapter.setRewards(rewards);
                    setState();

                    shareTitle = topic.getTitle();
                    Urltitle = topic.getContent();
                    if (null != topic.getAlbums() && topic.getAlbums().size() > 0) {
                        shareImageUrl = topic.getAlbums().get(0).getThumbnail();
                    } else {
                        shareImageUrl = ShareSDKApi.SHAREIMAGE;
                    }
                }
                if (currPage == 1) {
                    final ArrayList<PostsAlbum> tmpalbums = topic.getAlbums();
                    if (tmpalbums != null && tmpalbums.size() > 0) {
                        for (PostsAlbum postsAlbum : tmpalbums) {
                            if (postsAlbum.getUrl().contains(BBConstant.URL_VIDEO_PROTOCOL)) {
                                topic.setVideo(postsAlbum);
                                topic.setCategory("1");
                                break;
                            }
                        }
                    }
                    if (topic.getCategory().equals("1")) {//视频帖子
                        if (topic.getVideo() != null) {
                            if (NetworkUtility.getNetWorkConnectionType(this) == NetworkUtility.MOBILE) {
                                goPlay(topic.getVideo().getUrl());
                                network();
                            } else {
                                goPlay(topic.getVideo().getUrl());
                            }
                        }
                        video_layout.setVisibility(View.VISIBLE);
                    }
                }

                //评论
                ArrayList<Reply> replys = data.getData().getReplys();
                //热门评论
                ArrayList<Reply> hotReplys = topic.getHotReplys();

                channels = data.getData().getChannels();
                if (channels == null) {
                    channels = new ArrayList<>();
                }

                if (replys != null && replys.size() > 0) {
                    if (currPage == 1) {
                        detailList.clear();
                        if (hotReplys != null && hotReplys.size() > 0) {
                            detailList.addAll(hotReplys);
                            bbAdapter.setHotReplyCount(hotReplys.size());
                        }
                    }
                    detailList.addAll(replys);
                    bbAdapter.setDetailDatas(detailList);
                    currPage++;
                } else {
                    if (currPage == 1) {
                        detailList.clear();
                        recyclerView.setLoadingMoreEnabled(false);
                    } else {
                        recyclerView.noMoreLoading();
                    }
                }

                bbAdapter.notifyDataSetChanged();

            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_LIKE))) {
                AaskBeanData aaskBeanData = JsonUtil.getMode(response, AaskBeanData.class);
                if (null != aaskBeanData && aaskBeanData.getTaskData().size() > 0) {
                    for (AaskBeanData.AaskBean bean : aaskBeanData.getTaskData()) {
                        StringUtils.postToast2(GzTopicDetailActivity.this, bean.getName() + "", bean.getGold() + "");
                    }
                }
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICLIKE);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_UNLIKE))) {
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPIC_UNLIKE);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_COLLECTION))) {
                btn_collect.setImageResource(R.drawable.collect2);
                topic.setFavorited("1");
                showToast("收藏成功");
            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_CANCLE_COLLECTION))) {
                btn_collect.setImageResource(R.drawable.collect);
                topic.setFavorited("0");
                showToast("取消收藏");
            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_DELETE))) {
                showToast("删除成功");
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICDELETETOPIC);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
                finish();
            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_ADD_TO_DIGEST))) {
                if (nice.equals("0")) {
                    showToast("加精成功");
                    menuPopWindow.setisDigest(true);
                    topic.setNice("1");
                } else {
                    showToast("取消成功");
                    menuPopWindow.setisDigest(false);
                    topic.setNice("0");
                }
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICADDDIGEST);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);

            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_GET_GOLD_NUM))) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int goldNum = jsonObject.getInt("data");
                    goldDialog(goldNum);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_GOLD))) {
                showToast("谢谢客官打赏");
                updateRewardgold();
            } else if (tag.equals((ApiConfig.APIURL.URL_TOPICSHARE))) {
                AaskBeanData aaskBeanData = JsonUtil.getMode(response, AaskBeanData.class);
                if (null != aaskBeanData && aaskBeanData.getTaskData().size() > 0) {
                    for (AaskBeanData.AaskBean bean : aaskBeanData.getTaskData()) {
                        StringUtils.postToast2(GzTopicDetailActivity.this, bean.getName() + "", bean.getGold() + "");
                    }
                }
            }


        } else if (code == 6002) {
            showToast("帖子不存在");
        } else if (code == 9004) {

        } else if (code == 12) {
            showToast("请求频繁");
        } else if (code == 13) {
            showToast("不允许操作");
        } else if (code == 10) {
//            showToast("已点过赞");
        } else {
            showToast(response + "");
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        isLoading = false;
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        if (tag.equals((ApiConfig.APIURL.URL_POSTS_LIKE)) || tag.equals((ApiConfig.APIURL.URL_POSTS_UNLIKE))) {

        } else {
            ResultCode.toastVolleyError(this, volleyError);
        }
        if (currPage == 1) {
            if (tag.equals(ApiConfig.APIURL.URL_POSTS_DETAIL)) {
                setNoNetWork(new ReLoadClickListener() {
                    @Override
                    public void reload() {
                        getDetailReply();
                    }
                });
            }
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_play:
//                image_play.setVisibility(View.GONE);

                break;
            case R.id.main_back:
                finish();
                break;
            case R.id.btn_collect:
                if ("1".equals(topic.getFavorited())) {
                    cancleCollectionPost();
                } else {
                    collectionPost();
                }
                break;
            case R.id.btn_more_menu:
                try {
                    if (user.getId().equals(topic.getUser().getId())) {
                        showToast("Opps！你不能打赏自己哦");
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                getGoldNum();
                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_REWARD");


                break;
            case R.id.tv_comment:
                Intent intent = new Intent(GzTopicDetailActivity.this,
                        GzTopicReplyTopicActivity.class);
                intent.putExtra("topicId", topicId);
                startActivityForResult(intent, REQUEST_CODE_REPLYTOPIC);
                break;
            case R.id.ll_zan:
                if (topic == null) return;
                if ("1".equals(topic.getLiked())) {
                    unlikePost();
                    if (likeUsers.contains(user)) {
                        likeUsers.remove(user);
                    }
                    topic.setLiked("0");
                    topic.setLikes(Integer.parseInt(topic.getLikes()) - 1 + "");
                    setState();
                    bbAdapter.setLikeUsers(likeUsers);
                    bbAdapter.notifyDataSetChanged();

                } else {
                    imgv_zan.setImageResource(R.drawable.good2);
                    imgv_zan.startAnimation(scaleAnimation);
                    imgv_star1.setVisibility(View.GONE);
                    imgv_star2.setVisibility(View.GONE);
                    imgv_star1.startAnimation(starSet);
                    imgv_star2.startAnimation(starSet);
                    scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            imgv_star1.setVisibility(View.GONE);
                            imgv_star2.setVisibility(View.GONE);
                            likePost();
                            if (likeUsers == null) {
                                likeUsers = new ArrayList<>();
                            }
                            likeUsers.add(0, user);
                            topic.setLiked("1");
                            topic.setLikes(Integer.parseInt(topic.getLikes()) + 1 + "");
                            setState();
                            bbAdapter.setLikeUsers(likeUsers);
                            bbAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                }
                break;
            case R.id.tv_reward:
                showPopwindow(findViewById(R.id.tv_reward));
                break;
            case R.id.tv_red_packet:
                if ("0".equals(redState)) {
                    showOpenRedDialog(topic.getRedId(), false);
                } else {
//                    Intent intent2 = new Intent(GzTopicDetailActivity.this, GzRedPacketOpenActivity.class);
//                    intent2.putExtra("redId", topic.getRedId());
//                    intent2.putExtra("redType", topic.getRedType());
//                    startActivity(intent2);
                }

                break;
        }
    }

    private void likePost() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        topicApi.likePost(postsParam, this);
    }

    private void unlikePost() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        topicApi.unlikePost(postsParam, this);
    }

    private void collectionPost() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        topicApi.collectionPost(postsParam, this);
    }

    private void cancleCollectionPost() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        topicApi.cancleCollectionPost(postsParam, this);
    }

    class MyReplyClickListener implements BBDetailAdapter.ReplyOnclickListener {

        @Override
        public void even_more(final int position) {
            boolean res = false;
            boolean isDeleteReply = false;
            if (userPrefUtils.isDeletReply()) {
                isDeleteReply = true;
            }
            if (detailList.get(position).getUser().getId().equals(userPrefUtils.getUser().getId())
                    || topic.getUser().getId().equals(userPrefUtils.getUser().getId())) {
                res = true;
            }
            final TopicDetailDialog dialog = TopicDetailDialog.create(GzTopicDetailActivity.this, res, isDeleteReply);
            dialog.show();
            dialog.setReplyListener(new TopicDetailDialog.ReplyClickListener() {
                @Override
                public void replyClick() {
                    Reply clickReply = (Reply) detailList.get(position);
                    ActivityUtil.replyFloor(mActivity, topic, clickReply, position);
                    dialog.dismiss();
                }
            });
            dialog.setDeletelListener(new TopicDetailDialog.DeleteClickListener() {
                @Override
                public void deleteClick() {
                    deleteDialog("reply", (Reply) detailList.get(position));
                    dialog.dismiss();
                }
            });
            dialog.setReportListener(new TopicDetailDialog.ReportClickListener() {
                @Override
                public void reportClick() {
//                    Intent intent = new Intent(GzTopicDetailActivity.this, GzTopicReportActivity.class);
//                    intent.putExtra("topic", topic);
//                    intent.putExtra("reply", detailList.get(position));
//                    startActivity(intent);
//                    dialog.dismiss();
                }
            });
        }

        @Override
        public void reply(int position) {
            Reply clickReply = (Reply) detailList.get(position);
            ActivityUtil.replyFloor(mActivity, topic, clickReply, position);
        }

        @Override
        public void replyComment(final int position, final Reply reply) {
//            Reply clickReply = (Reply) detailList.get(position);
//            ActivityUtil.replyFloorComment(mActivity, topic, clickReply, reply, position);

            boolean res = false;
            boolean isDeleteReply = false;
            if (userPrefUtils.isDeletReply()) {
                isDeleteReply = true;
            }
            if (reply.getUser().getId().equals(userPrefUtils.getUser().getId())
                    || topic.getUser().getId().equals(userPrefUtils.getUser().getId())) {
                res = true;
            }
            final TopicDetailDialog dialog = TopicDetailDialog.create(GzTopicDetailActivity.this, res, isDeleteReply);
            dialog.setTv1(reply);
            dialog.show();
            dialog.setReplyListener(new TopicDetailDialog.ReplyClickListener() {
                @Override
                public void replyClick() {
                    Reply clickReply = (Reply) detailList.get(position);
                    ActivityUtil.replyFloorComment(mActivity, topic, clickReply, reply, position);
                    dialog.dismiss();
                }
            });
            dialog.setDeletelListener(new TopicDetailDialog.DeleteClickListener() {
                @Override
                public void deleteClick() {
                    Reply clickReply = (Reply) detailList.get(position);
                    deleteDialog2("reply", clickReply, reply);
                    dialog.dismiss();
                }
            });
            dialog.setReportListener(new TopicDetailDialog.ReportClickListener() {
                @Override
                public void reportClick() {
//                    Intent intent = new Intent(GzTopicDetailActivity.this, GzTopicReportActivity.class);
//                    intent.putExtra("topic", topic);
//                    intent.putExtra("reply", reply);
//                    startActivity(intent);
                    dialog.dismiss();
                }
            });
        }

        @Override
        public void more_reply(int position, Reply reply) {
            ActivityUtil.replyFloor(mActivity, topic, reply, position);
        }

        @Override
        public void replyTopic() {
            Intent intent = new Intent(GzTopicDetailActivity.this,
                    GzTopicReplyTopicActivity.class);
            intent.putExtra("topicId", topicId);
            startActivityForResult(intent, REQUEST_CODE_REPLYTOPIC);
        }

        @Override
        public void like(int position, final ImageView imgv_zan) {
            final Reply clickReply = (Reply) detailList.get(position);
            if (clickReply.isLiked()) {
                replyunlikePost(clickReply);
                imgv_zan.setImageResource(R.drawable.bb_zan_selector);
                imgv_zan.setSelected(false);
                clickReply.setLiked(false);
                clickReply.setLikes(clickReply.getLikes() - 1);
                bbAdapter.notifyDataSetChanged();
            } else {
                replylikePost(clickReply);
                imgv_zan.setImageResource(R.drawable.good2);
                imgv_zan.startAnimation(scaleAnimation);
                scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        imgv_zan.setImageResource(R.drawable.bb_zan_selector);
                        imgv_zan.setSelected(true);
                        clickReply.setLiked(true);
                        clickReply.setLikes(clickReply.getLikes() + 1);
                        bbAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });

            }


        }

        @Override
        public void order() {

            if (order.equals("0")) {
                order = "1";

            } else {
                order = "0";
            }
            currPage = 1;
            getDetailReply();
            MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_DESC");
        }

    }

    private void replylikePost(Reply reply) {
        PostsParam param = new PostsParam();
        param.setUserId(userPrefUtils.getUser().getId() + "");
        param.setPostsId(topicId);
        param.setReplyId(reply.getId() + "");
        topicApi.likereplyPost(param, new ReplyLikePostListener(reply, "like"));
    }

    private void replyunlikePost(Reply reply) {
        PostsParam param = new PostsParam();
        param.setUserId(userPrefUtils.getUser().getId() + "");
        param.setPostsId(topicId);
        param.setReplyId(reply.getId() + "");
        topicApi.unlikereplyPost(param, new ReplyLikePostListener(reply, "unlike"));
    }

    /**
     * 点赞的监听
     */
    class ReplyLikePostListener implements VolleyListener {
        private Reply reply;
        private String type;

        public ReplyLikePostListener(Reply reply, String type) {
            this.reply = reply;
            this.type = type;
        }

        @Override
        public void onStart(String tag) {

        }

        @Override
        public void onSuccess(String response, String tag) {
            if (JSONHelper.isSuccess(response)) {
                if (type.equals("like")) {
//                    reply.setLikesCount((Integer.parseInt(reply.getLikesCount())+1)+"");
//                    reply.setLiked(true);
                } else {
//                    reply.setLikesCount((Integer.parseInt(reply.getLikesCount())-1)+"");
//                    reply.setLiked(false);
                }
//                bbAdapter.notifyDataSetChanged();

            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
// dismissDialog();
            ResultCode
                    .toastVolleyError(GzTopicDetailActivity.this, volleyError);
        }
    }


    class MyOpenRedClickListener implements BBDetailAdapter.OpenRedClickListener {
        @Override
        public void OpenRedDialog() {
            if ("0".equals(redState)) {
                showOpenRedDialog(topic.getRedId(), false);
            } else {
//                Intent intent2 = new Intent(GzTopicDetailActivity.this, GzRedPacketOpenActivity.class);
//                intent2.putExtra("redId", topic.getRedId());
//                intent2.putExtra("redType", topic.getRedType());
//                startActivity(intent2);
            }
        }
    }

    class addRewardClickListener implements RewardAdapter.onAddRewardClickListener {
        @Override
        public void addReward() {
            try {
                if (user.getId().equals(topic.getUser().getId())) {
                    showToast("Opps！你不能打赏自己哦");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            getGoldNum();
            MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_REWARD");
        }
    }


    // 删除贴子
    @Subscribe
    public void deleteReplyEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICDELETETOPICORREPLY.equals(event)) {
            Reply reply = (Reply) map.get("reply");
            if (detailList.contains(reply)) {
                detailList.remove(reply);
            }
            bbAdapter.setDetailDatas(detailList);
            bbAdapter.notifyDataSetChanged();
        }
    }

    // 修改贴子
    @Subscribe
    public void updateEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICCREATENEOTOPIC.equals(event)) {
//            showToast("修改成功");
            topic = (Topic) map.get("topic");
            if (topic.getAudios() != null && topic.getAudios().size() > 0) {
                topic.getAlbums().add(topic.getAudios().get(0));
            }
            bbAdapter.setTopic(topic);
            bbAdapter.notifyDataSetChanged();

        }
    }

    // 添加回复
    @Subscribe
    public void addReplyEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICREPLYLIST.equals(event)) {
            try {
                int pos = (int) map.get("clickposition");
                Reply reply = detailList.get(pos);
                ArrayList<Reply> replys = (ArrayList<Reply>) map.get("replys");
                int remainReplys = (int) map.get("remainReplys");
                if (reply.getReplys() == null || reply.getReplys().size() < 3) {
                    reply.setReplys(replys);
                }
                reply.setRemainReplys(remainReplys);
                int likes = (int) map.get("likes");
                boolean liked = (boolean) map.get("liked");
                reply.setLikes(likes);
                reply.setLiked(liked);
                bbAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == REQUEST_CODE_REPLYTOPIC) {
                showToast("回复成功");
                //回复内容添加到列表
                Reply reply = (Reply) data.getSerializableExtra("reply");
                if (order.equals("0")) {
                    if (detailList.size() < pageSize) {
                        detailList.add(detailList.size(), reply);
                    }
                } else {
                    if (topic.getHotReplys() != null && topic.getHotReplys().size() > 0) {
                        detailList.add(topic.getHotReplys().size(), reply);
                    } else {
                        detailList.add(0, reply);
                    }
                }
                topic.setReplys(Integer.parseInt(topic.getReplys()) + 1 + "");
                setState();
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICREPLYS);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
                bbAdapter.setDetailDatas(detailList);
                bbAdapter.notifyDataSetChanged();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //点赞
    private void setState() {
        imgv_zan.setImageResource(R.drawable.bb_zan_selector);
        if (topic.getLiked() != null && "1".equals(topic.getLiked())) {
            imgv_zan.setSelected(true);
        } else {
            imgv_zan.setSelected(false);
        }
        if (Integer.parseInt(topic.getLikes()) > 0) {
            tv_zan.setText(topic.getLikes());
        } else {
            tv_zan.setText("赞");
        }
        if (Integer.parseInt(topic.getReplys()) > 0) {
            tv_comment.setText(topic.getReplys());
        } else {
            tv_comment.setText("评论");
        }
        if (null != topic.getFavorited() && "1".equals(topic.getFavorited())) {
            btn_collect.setImageResource(R.drawable.collect2);
        } else {
            btn_collect.setImageResource(R.drawable.collect);
        }
        if (user.getId().equals(topic.getUser().getId())) {
            isMyTopic = true;
        }
    }


    /**
     */
    protected void showPopwindow(View view) {
        try {
            if (topic == null) return;
            boolean isAddDigest = false;
            if (topic.getNice().equals("1")) {
                isAddDigest = true;
            }
            boolean hasChannel = false;
            if (channels != null && channels.size() > 0) {
                hasChannel = true;
            }
            menuPopWindow = MenuPopWindow.getInstance(this, isMyTopic, isAddDigest, hasChannel);
            menuPopWindow.showPopWindow(view);
            menuPopWindow.setMenuClickListener(new MyPopWindowClickListener());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyPopWindowClickListener implements MenuPopWindow.MenuClickListener, ChannelsSelectDialog.ChannelListViewListener {

        @Override
        public void onMenuClick(String type) {
            if (type.equals(MenuPopWindow.tag_look_owner)) {
                if (isOwner.equals("false")) {
                    isOwner = "true";
                } else {
                    isOwner = "false";
                }
                currPage = 1;
                getDetailReply();
                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_OWNER");


            } else if (type.equals(MenuPopWindow.tag_order)) {
                if (order.equals("0")) {
                    order = "1";
                } else {
                    order = "0";
                }
                currPage = 1;
                getDetailReply();
                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_DESC");
            } else if (type.equals(MenuPopWindow.tag_share)) {
                showShare();
                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_SHARE");
            } else if (type.equals(MenuPopWindow.tag_delete)) {
                if (!TextUtils.isEmpty(topic.getRedId())) {
                    deleteDialog1("topic", null);
                } else {
                    deleteDialog("topic", null);
                }
                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_DELETE");
            } else if (type.equals(MenuPopWindow.tag_add_to_digest)) {
                addToDigest();
            } else if (type.equals(MenuPopWindow.tag_update)) {
                Intent intent = new Intent(mActivity, GzTopicSendActivity.class);
                intent.putExtra("topic", topic);
                mActivity.startActivity(intent);

            } else if (type.equals(MenuPopWindow.tag_report)) {
//                Intent intent = new Intent(GzTopicDetailActivity.this, GzTopicReportActivity.class);
//                intent.putExtra("topic", topic);
//                startActivity(intent);
//                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_BAD_REPORT");
            } else if (type.equals(MenuPopWindow.tag_link)) {
                try {
                    ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    clip.setText(ShareSDKApi.getTopicShare(topic.getPostsId()));
                    Toast.makeText(GzTopicDetailActivity.this, "已复制到剪切板", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(GzTopicDetailActivity.this, "复制到剪切板失败", Toast.LENGTH_LONG).show();
                }
                MobclickAgent.onEvent(mActivity, "EC_POST_DETAIL_COPY_LINK");
            } else if (type.equals(MenuPopWindow.tag_add_channel)) {
                ChannelsSelectDialog dialog = new ChannelsSelectDialog(GzTopicDetailActivity.this, GuZhiApplication.getInstance().getChannelList());
                dialog.setListenner(this);
                dialog.show();
            } else if (type.equals(MenuPopWindow.tag_remove_channel)) {
                ChannelsSelectDialog dialog = new ChannelsSelectDialog(GzTopicDetailActivity.this, channels);
                dialog.setListenner(this);

                dialog.show();
            }
        }

        @Override
        public void onItemClick(int position, TopicChannel data) {
            if (channels != null && channels.size() > 0) {
                // 移出
                PostsParam postsParam = new PostsParam();
                postsParam.setUserId(user.getId() + "");
                postsParam.setPostsId(topicId);
                postsParam.setChannelId(data.getChannelId());
                topicApi.removeChannel(postsParam, new VolleyListener() {
                    @Override
                    public void onStart(String tag) {
                        Toast.makeText(GuZhiApplication.getInstance(), "正在处理", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(String response, String tag) {
                        int code = JSONHelper.getResultCode(response);
                        if (code == 0) {
                            Toast.makeText(GuZhiApplication.getInstance(), "处理成功", Toast.LENGTH_SHORT).show();
                        } else if (code == -1) {
                            Toast.makeText(GuZhiApplication.getInstance(), "处理失败", Toast.LENGTH_SHORT).show();
                        } else if (code == 13) {
                            Toast.makeText(GuZhiApplication.getInstance(), "您没有权限", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFaile(VolleyError volleyError, String tag) {
                        Toast.makeText(GuZhiApplication.getInstance(), "处理失败", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                //移进
                PostsParam postsParam = new PostsParam();
                postsParam.setUserId(user.getId() + "");
                postsParam.setPostsId(topicId);
                postsParam.setChannelId(data.getChannelId());
                topicApi.addChannel(postsParam, new VolleyListener() {
                    @Override
                    public void onStart(String tag) {
                        Toast.makeText(GuZhiApplication.getInstance(), "正在处理", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(String response, String tag) {
                        int code = JSONHelper.getResultCode(response);
                        if (code == 0) {
                            Toast.makeText(GuZhiApplication.getInstance(), "处理成功", Toast.LENGTH_SHORT).show();
                        } else if (code == -1) {
                            Toast.makeText(GuZhiApplication.getInstance(), "处理失败", Toast.LENGTH_SHORT).show();
                        } else if (code == 13) {
                            Toast.makeText(GuZhiApplication.getInstance(), "您没有权限", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFaile(VolleyError volleyError, String tag) {
                        Toast.makeText(GuZhiApplication.getInstance(), "处理失败", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }
    }

    private void deleteDialog(final String type, final Reply reply) {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.show();
        dialog.setCancelable(true);
        dialog.setTitle("提示");
        if (userPrefUtils.isDeletTopic()) {
            dialog.setContent("正在使用管理员删除功能，确定删除这个帖子么？");
        } else {
            dialog.setContent("是否删除");
        }
        dialog.setSubmittext("确定");
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                if (type.equals("topic")) {
                    deleteTopic();
                } else if (type.equals("reply")) {
                    deleteReply(reply);
                }
                dialog.dismiss();

            }
        });
    }

    private void deleteDialog2(final String type, final Reply clickReply, final Reply reply) {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.show();
        dialog.setCancelable(true);
        dialog.setTitle("提示");
        if (userPrefUtils.isDeletTopic()) {
            dialog.setContent("正在使用管理员删除功能，确定删除这个帖子么？");
        } else {
            dialog.setContent("是否删除");
        }
        dialog.setSubmittext("确定");
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                if (type.equals("topic")) {
                    deleteTopic();
                } else if (type.equals("reply")) {
                    deleteReply2(clickReply, reply);
                }
                dialog.dismiss();

            }
        });
    }

    private void deleteDialog1(final String type, final Reply reply) {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.show();
        dialog.setCancelable(true);
        dialog.setTitle("提示");
        dialog.setContent("这是一个红包贴，删除后剩余金额将在24小时内返还到钱包中，确定删除？");
        dialog.setSubmittext("确定");
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                if (type.equals("topic")) {
                    deleteTopic();
                } else if (type.equals("reply")) {
                    deleteReply(reply);
                }
                dialog.dismiss();

            }
        });
    }

    /**
     * 获取金币数量
     */
    private void getGoldNum() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setUserId(user.getId() + "");
        topicApi.getGoldNum(postsParam, this);
    }

    private void goldDialog(final int userGoldNum) {
        final GoldDialog dialog = GoldDialog.create(this, true);
        dialog.show();
        dialog.getTv_num().setText("你拥有的金币数量:  " + userGoldNum);
        dialog.setSubmitListener(new GoldDialog.SubmitClickListener() {

            @Override
            public void submitClick(int gold) {
                if (gold > userGoldNum) {
                    showToast("你没有足够的金币");
                } else {
                    gold(gold);
                }
                reward_gold = gold;
                dialog.dismiss();
            }
        });
    }

    /**
     * 加精
     */
    private void addToDigest() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        nice = topic.getNice();
        if (topic.getNice().equals("0")) {
            postsParam.setState("1");
        } else {
            postsParam.setState("0");
        }

        topicApi.addToDigest(postsParam, this);
    }

    /**
     * 删除帖子
     */
    private void deleteTopic() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        topicApi.deleteTopic(postsParam, this);
    }

    /**
     * 删除回复
     */
    private void deleteReply(Reply reply) {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setReplyId(reply.getId() + "");
        postsParam.setUserId(user.getId() + "");
        topicApi.deleteReply(postsParam, new DelReplyListener(reply));
    }

    private void deleteReply2(Reply clickReply, Reply reply) {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setReplyId(reply.getId() + "");
        postsParam.setUserId(user.getId() + "");
        topicApi.deleteReply(postsParam, new DelReplyListener2(clickReply, reply));
    }

    /**
     * 赏金币
     */
    private void gold(int gold) {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(user.getId() + "");
        postsParam.setGold(gold + "");
        topicApi.gold(postsParam, this);
    }

    private void updateRewardgold() {
        if (rewards != null) {
            ArrayList<RewardUser> rewardUsers = rewards.getUsers();
            if (rewards.getGold() == 0) {//没打赏过
                rewards.setGold(reward_gold);
                rewards.setNumber(rewards.getNumber() + 1);
                RewardUser rewardUser = new RewardUser();
                rewardUser.setGold(reward_gold);
                rewardUser.setUser(user);
                rewardUsers.add(rewardUser);
                rewards.setUsers(rewardUsers);
            } else {  //已打赏过
                for (int i = 0; i < rewardUsers.size(); i++) {
                    RewardUser tmpRewardUser = rewardUsers.get(i);
                    User tmpUser = tmpRewardUser.getUser();
                    if (tmpUser.getId().equals(user.getId())) {
                        tmpRewardUser.setGold(tmpRewardUser.getGold() + reward_gold);
                        rewards.setGold(rewards.getGold() + reward_gold);
                    }
                }
            }
        } else {
            rewards = new Rewards();
            rewards.setGold(reward_gold);
            rewards.setNumber(1);
            ArrayList<RewardUser> rewardUsers = new ArrayList<>();
            RewardUser rewardUser = new RewardUser();
            rewardUser.setGold(reward_gold);
            rewardUser.setUser(user);
            rewardUsers.add(rewardUser);
            rewards.setUsers(rewardUsers);
        }
        RewardUserComparator comparator = new RewardUserComparator();
        Collections.sort(rewards.getUsers(), comparator);
        bbAdapter.setRewards(rewards);
        bbAdapter.notifyDataSetChanged();
    }


    class DelReplyListener implements VolleyListener {

        Reply deleteReply;

        public DelReplyListener(Reply deleteReply) {
            super();
            this.deleteReply = deleteReply;
        }

        @Override
        public void onStart(String tag) {
            showDialog("正在删除...", true);
        }

        @Override
        public void onSuccess(String response, String tag) {
            dismissDialog();
            if (JSONHelper.isSuccess(response)) {
                detailList.remove(deleteReply);
                if (detailList.contains(deleteReply)) { //删除一次列表如果还包含此评论，说明此评论也是热门评论
                    detailList.remove(deleteReply);
                    bbAdapter.setHotReplyCount(bbAdapter.getHotReplyCount() - 1);
                }
                topic.setReplys(Integer.parseInt(topic.getReplys()) - 1 + "");
                try {
                    setState();
                } catch (Exception e) {

                }
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICREPLYS);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
                bbAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(GzTopicDetailActivity.this, "删除失败",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            dismissDialog();
            ResultCode
                    .toastVolleyError(GzTopicDetailActivity.this, volleyError);
        }

    }

    class DelReplyListener2 implements VolleyListener {
        Reply clickReply;
        Reply deleteReply;

        public DelReplyListener2(Reply clickReply, Reply deleteReply) {
            super();
            this.deleteReply = deleteReply;
            this.clickReply = clickReply;
        }

        @Override
        public void onStart(String tag) {
            showDialog("正在删除...", true);
        }

        @Override
        public void onSuccess(String response, String tag) {
            dismissDialog();
            if (JSONHelper.isSuccess(response)) {
                clickReply.getReplys().remove(deleteReply);
                bbAdapter.notifyDataSetChanged();
//                if(clickReply.getReplys().contains(deleteReply)){ //删除一次列表如果还包含此评论，说明此评论也是热门评论
//                    clickReply.getReplys().remove(deleteReply);
//                    bbAdapter.setHotReplyCount(bbAdapter.getHotReplyCount()-1);
//                }
            } else {
                Toast.makeText(GzTopicDetailActivity.this, "删除失败",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            dismissDialog();
            ResultCode
                    .toastVolleyError(GzTopicDetailActivity.this, volleyError);
        }

    }

    //拆红包
    private void showOpenRedDialog(final String redId, boolean isno) {
        final OpenRedDialog dialog = OpenRedDialog.create(this, true);
        if (!dialog.isShowing() && !this.isFinishing()) {
            dialog.show();
        }
        dialog.setNopakeText(isno);
        dialog.getNick().setText(topic.getUser().getNick() + "");
        glideUtils.Glidde_loadCropCircleImage(this, topic.getUser().getLogo(),
                dialog.getLogo());
        dialog.setOpenClickListener(new OpenRedDialog.OpenClickListener() {
            @Override
            public void openClick() {
                dialog.dismiss();
                openRedPacket(redId, dialog);
            }

            @Override
            public void otherClick() {
                dialog.dismiss();
//                Intent intent = new Intent(GzTopicDetailActivity.this, GzRedPacketOpenActivity.class);
//                intent.putExtra("redId", topic.getRedId());
//                intent.putExtra("redType", topic.getRedType());
//                startActivity(intent);
            }
        });
    }


    /**
     * 拆红包
     */
    private void openRedPacket(String redId, OpenRedDialog dialog) {
        if (isLoading) {
            return;
        }
        RechargeParam rechargeParam = new RechargeParam();
        rechargeParam.setRedId(redId);
        rechargeParam.setRedType(topic.getRedType() + "");
        rechargeApi.openRed(rechargeParam, new openRedListener(dialog));
    }

    class openRedListener implements VolleyListener {
        OpenRedDialog dialog;

        public openRedListener(OpenRedDialog dialog) {
            this.dialog = dialog;
        }

        @Override
        public void onStart(String tag) {
            isLoading = true;
            showDialog("正在拆红包...", true);
        }

        @Override
        public void onSuccess(String response, String tag) {
            isLoading = false;
            dismissDialog();
            if (JSONHelper.isSuccess(response)) {

//                RedOpenData data = JsonUtil.getMode(response, RedOpenData.class);
//                RedOpenEntity entity = data.getData();
                dialog.dismiss();
//                Intent intent = new Intent(GzTopicDetailActivity.this, GzRedPacketOpenActivity.class);
//                intent.putExtra("redId", topic.getRedId());
//                intent.putExtra("redType", topic.getRedType());
//                startActivity(intent);
                // 记录红包已打开过
                topic.setRedState("1");
                redState = "1";
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICREDSTATE);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);

            } else if (JSONHelper.getResultCode(response) == 9140) {
                Toast.makeText(GzTopicDetailActivity.this, JSONHelper.getResultMsg(response) + "", Toast.LENGTH_SHORT).show();
            } else if (JSONHelper.getResultCode(response) == 9141) {
                showToast(JSONHelper.getResultMsg(response) + "");
            } else if (JSONHelper.getResultCode(response) == 9142) {
                // 已打开过
                dialog.dismiss();
//                Intent intent = new Intent(GzTopicDetailActivity.this, GzRedPacketOpenActivity.class);
//                intent.putExtra("redId", topic.getRedId());
//                intent.putExtra("redType", topic.getRedType());
//                startActivity(intent);
                redState = "1";
                topic.setRedState("1");
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICREDSTATE);
                hashMap.put("topic", topic);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);

            } else {
                Toast.makeText(GzTopicDetailActivity.this, "领取失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            dismissDialog();
            Toast.makeText(GzTopicDetailActivity.this, "领取失败", Toast.LENGTH_SHORT).show();
            isLoading = false;
        }

    }

    String shareTitle = "EDG俱乐部";
    String Urltitle = "EDG俱乐部";
    String shareImageUrl = ShareSDKApi.SHAREIMAGE;

    private void showShare() {

        ShareSDKApi.showShare(this, shareTitle,
                Urltitle, ApiConfig.USER_POST_SHARE + topicId + "&app=false", shareImageUrl, new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Message message = new Message();
                        message.what = 0;
                        message.obj = platform;
                        shareHandler.sendMessage(message);
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = platform;
                        shareHandler.sendMessage(message);
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        Message message = new Message();
                        message.what = 2;
                        message.obj = platform;
                        shareHandler.sendMessage(message);
                    }
                });
    }

    Handler shareHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Platform platform = (Platform) msg.obj;
            if (msg.what == 0) {
                if (QQ.NAME.equals(platform.getName())) {
                    shareTopic(0, topic.getTitle() + "_" + topicId);
                } else if (Wechat.NAME.equals(platform.getName())) {
                    shareTopic(1, topic.getTitle() + "_" + topicId);
                } else if (SinaWeibo.NAME.equals(platform.getName())) {
                    shareTopic(2, topic.getTitle() + "_" + topicId);
                }
                showToast(StringUtils.getString(R.string.share_yes));
            } else if (msg.what == 1) {
                if (QQ.NAME.equals(platform.getName())) {
                    if (CommonUtils.checkPackage(GzTopicDetailActivity.this,
                            "com.tencent.mobileqq")
                            || CommonUtils.checkPackage(GzTopicDetailActivity.this, "com.tencent.qqlite")) {
                        Platform googlePlus1 = ShareSDK.getPlatform(QQ.NAME);
                        googlePlus1.SSOSetting(false);  //设置false表示使用SSO授权方式
                        googlePlus1.showUser(null);
                    } else {
                        showToast("没有安装QQ客户端");
                    }
                } else if (Wechat.NAME.equals(platform.getName())) {
                    if (CommonUtils.checkPackage(GzTopicDetailActivity.this,
                            "com.tencent.mm")) {
                        Platform googlePlus3 = ShareSDK.getPlatform(Wechat.NAME);
                        googlePlus3.SSOSetting(false);  //设置false表示使用SSO授权方式
                        googlePlus3.showUser(null);
                    } else {
                        showToast("没有安装微信客户端");
                    }

                } else {
                    showToast(StringUtils.getString(R.string.share_no));
                }
            } else if (msg.what == 2) {
                showToast(StringUtils.getString(R.string.share_del));
            }
        }
    };

    private void shareTopic(int type, String title) {
        TopicReportParam topicReportParam = new TopicReportParam();
        topicReportParam.setUserId(userPrefUtils.getUser().getId());
        topicReportParam.setTitle(title);
        topicReportParam.setType(type + "");
        topicApi.shareTopic(topicReportParam, this);
    }

    /*******************************
     * youku
     *****************************************************/
    private YoukuBasePlayerManager basePlayerManager;
    // 播放器控件
    private YoukuPlayerView mYoukuPlayerView;
    private LinearLayout video_layout;

    // 需要播放的视频id
    private String vid;
    // 需要播放的本地视频的id
    private String local_vid;

    // 标示是否播放的本地视频
    private boolean isFromLocal = false;

    private String id = "";

    // YoukuPlayer实例，进行视频播放控制
    private YoukuPlayer youkuPlayer;

    private void initVideoView() {
        video_layout = (LinearLayout) findViewById(R.id.video_layout);
        basePlayerManager = new YoukuBasePlayerManager(this) {

            @Override
            public void setPadHorizontalLayout() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onInitializationSuccess(YoukuPlayer player) {
                // TODO Auto-generated method stub
                // 初始化成功后需要添加该行代码
                addPlugins();

                // 实例化YoukuPlayer实例
                youkuPlayer = player;

                // 进行播放
//            goPlay();
            }

            @Override
            public void onSmallscreenListener() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onFullscreenListener() {
                // TODO Auto-generated method stub

            }
        };
        basePlayerManager.onCreate();

        // 通过上个页面传递过来的Intent获取播放参数
        getIntentData(getIntent());

//    if (TextUtils.isEmpty(id)) {
//        vid = "XODQwMTY4NDg0"; // 默认视频
//    } else {
//        vid = id;
//    }

        // 播放器控件
        mYoukuPlayerView = (YoukuPlayerView) this
                .findViewById(R.id.full_holder1);
        //控制竖屏和全屏时候的布局参数。这两句必填。
        mYoukuPlayerView
                .setSmallScreenLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
        mYoukuPlayerView
                .setFullScreenLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT));
        // 初始化播放器相关数据
        try {
            mYoukuPlayerView.initialize(basePlayerManager);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //添加播放器的回调
        basePlayerManager.setPlayerListener(new YoukuPlayerListener() {
            @Override
            public void onCompletion() {
                // TODO Auto-generated method stub
                super.onCompletion();
            }

            @Override
            public void onStartBuffering() {
                // TODO Auto-generated method stub
                super.onStartBuffering();
            }
            //...
        });
    }


    @Override
    public void onBackPressed() { // android系统调用
        Logger.d("sgh", "onBackPressed before super");
        super.onBackPressed();
        Logger.d("sgh", "onBackPressed");
        basePlayerManager.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        //更改为LANDSCAPE
        switch (newConfig.orientation) {
            case (Configuration.ORIENTATION_LANDSCAPE):
//如果转换为横向屏时，有要做的事，请写在这里
                if (null != actionBar)
                    actionBar.hide();
                isShowingDialog(true);
                break;
//更改为PORTRAIT
            case (Configuration.ORIENTATION_PORTRAIT):
//如果转换为竖向屏时，有要做的事，请写在这里
                if (null != actionBar)
                    actionBar.show();
                isShowingDialog(false);
                break;
        }
        basePlayerManager.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        basePlayerManager.onDestroy();
        if (menuPopWindow != null) {
            menuPopWindow.setInstance(null);
        }
        unregisterReceiver(myNetReceiver);

    }

    @Override
    public void onLowMemory() { // android系统调用
        super.onLowMemory();
        basePlayerManager.onLowMemory();
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            basePlayerManager.onPause();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            basePlayerManager.onResume();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onSearchRequested() { // android系统调用
        return basePlayerManager.onSearchRequested();
    }

    @Override
    protected void onStart() {
        super.onStart();
        basePlayerManager.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        basePlayerManager.onStop();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);

        // 通过Intent获取播放需要的相关参数
        getIntentData(intent);

        // 进行播放
//        goPlay();
    }

    /**
     * 获取上个页面传递过来的数据
     */
    private void getIntentData(Intent intent) {

        if (intent != null) {
            // 判断是不是本地视频
            isFromLocal = intent.getBooleanExtra("isFromLocal", false);

            if (isFromLocal) { // 播放本地视频
                local_vid = intent.getStringExtra("video_id");
            } else { // 在线播放
                id = intent.getStringExtra("vid");
            }
        }

    }

    private void goPlay(String url) {
        String id = url.replace(BBConstant.URL_VIDEO_PROTOCOL, "");
        if (TextUtils.isEmpty(id)) {
            vid = "XODQwMTY4NDg0"; // 默认视频
        } else {
            vid = id;
        }
        if (isFromLocal) { // 播放本地视频
            youkuPlayer.playLocalVideo(local_vid);
        } else { // 播放在线视频
            youkuPlayer.playVideo(vid);
        }

        // XNzQ3NjcyNDc2
        // XNzQ3ODU5OTgw
        // XNzUyMzkxMjE2
        // XNzU5MjMxMjcy 加密视频
        // XNzYxNzQ1MDAw 万万没想到
        // XNzgyODExNDY4 魔女范冰冰扑倒黄晓明
        // XNDcwNjUxNzcy 姐姐立正向前走
        // XNDY4MzM2MDE2 向着炮火前进
        // XODA2OTkwMDU2 卧底韦恩突出现 劫持案愈发棘手
        // XODUwODM2NTI0 会员视频
        // XODQwMTY4NDg0 一个人的武林
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean managerKeyDown = basePlayerManager.onKeyDown(keyCode, event);
        if (basePlayerManager.shouldCallSuperKeyDown()) {
            return super.onKeyDown(keyCode, event);
        } else {
            return managerKeyDown;
        }

    }

    private DeleteDialog dialog;

    private void network() {
        try {
            if (dialog != null) return;
            dialog = DeleteDialog.create(GzTopicDetailActivity.this, true);
            dialog.setTitle(StringUtils.getString(R.string.prompt));
            dialog.setContent(StringUtils.getString(R.string.play_video_tip));
            dialog.show();
            dialog.getTvOk().setText(StringUtils.getString(R.string.ok));
            dialog.getTvOk().setTextColor(0xff0096ff);
            dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

                @Override
                public void cancelClick() {
                    dialog.dismiss();
                    dialog = null;
                    youkuPlayer.getmMediaPlayerDelegate().pause();
//                image_play.setVisibility(View.VISIBLE);
                }
            });

            dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

                @Override
                public void submitClick() {
                    dialog.dismiss();
                    dialog = null;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {

                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        /////WiFi网络

                    } else if (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        /////有线网络

                    } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        /////////移动网络
//                        youkuPlayer.getmMediaPlayerDelegate().stop();
                        if (topic != null && topic.getCategory().equals("1")) {
                            network();
                        }
                    }
                } else {
                    ////////网络断开
//                    network();
                }
            }
        }
    };


}
